const mongoose = require('mongoose')
const { DbLog } = require('../modules/log')

const { DB_CONNECTION } = require('../env')
const { timestamp } = require('../utils')

// 创建插件函数
function setTimestampsToUnix(schema) {
  schema.add({
    created_at: {
      type: Number,
      index: true,
      default: timestamp,
    },
    updated_at: {
      type: Number,
      index: true,
      default: timestamp,
    },
  })
  schema.pre('save', function (next) {
    if (this.created_at === undefined) {
      this.created_at = timestamp()
    }
    this.updated_at = timestamp()
    next()
  })
}

mongoose.plugin(setTimestampsToUnix);

function main() {
  return mongoose.connect(DB_CONNECTION)
}

function connect() {
  return main().then(() => {
    DbLog('connect successfully.')
  }).catch(err => {
    DbLog(`connect with error:${err.message}.`)
  })
}

module.exports = connect